package cn.tedu.sp06.fallback;

import cn.tedu.web.util.JsonResult;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * 通过 zuul网关，调用后台商品服务失败时，会执行这段代码，
 * 向客户端返回降级结果
 */
@Component
public class OrderFB implements FallbackProvider {
    /**
     * 设置当前降级类，是针对哪个服务的降级类
     * - item-service: 只针对商品服务降级
     * - *： 针对所有服务都应用当前降级类
     * - null： 同*
     * @return
     */
    @Override
    public String getRoute() {
        return "order-service";
    }

    /**
     * 发送给客户端的降级结果，封装在response对象中
     * @param route
     * @param cause
     * @return
     */
    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR; //返回一个500错误 {code:500,text:"服务器内部错"}
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR.value(); //500
            }

            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(); //服务器内部错
            }

            @Override
            public void close() {
                //用来关闭流
                //ByteArrayInputStream 不需要关闭
            }

            @Override
            public InputStream getBody() throws IOException {
                // JsonResult {code:500, msg:"调用商品服务失败，data:null}
                String json = JsonResult.err().code(500).msg("调用订单服务失败").toString();
                return new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)); //或者直接用字符串"UTF-8"
            }

            @Override
            public HttpHeaders getHeaders() {
                //Content-Type: application/json;charset=UTF-8
                HttpHeaders h = new HttpHeaders();
                h.add("Content-Type","application/json;charset=UTF-8");
                return h;
            }
        };
    }
}
